import { Component, OnInit,Input, Output,EventEmitter, forwardRef } from '@angular/core';
import { SafeStyle,DomSanitizer } from '@angular/platform-browser';
import { NG_VALUE_ACCESSOR,ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'el-switch',
  templateUrl: './switch.component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: SwitchComponent,
    multi: true
}],
})
export class SwitchComponent implements OnInit,ControlValueAccessor {
  private controlChange:any = function () { };
  private controlTouch:any = function () { };
  private sanitizer:any;
  @Input() disabled: boolean = false;
  @Input() name: string = '';
  @Input() width: number = 0;
  @Input('active-icon-class') activeIconClass: string = '';
  @Input('inactive-icon-class') inactiveIconClass: string = '';
  @Input('active-text') activeText: string = '';
  @Input('inactive-text') inactiveText: string = '';
  @Input('active-color') activeColor: string = '#409EFF';
  @Input('inactive-color') inactiveColor: string = '#C0CCDA';
  @Input() model: boolean = false;
  @Output('change') modelChange: EventEmitter<any> = new EventEmitter();
  @Input() hasText: boolean = false;
  @Input() realWidth: number = 0;
  @Input() coreStyles!: SafeStyle;
  @Input() iconTransform!: SafeStyle;
  
  constructor(sanitizer: DomSanitizer) {
      this.sanitizer = sanitizer;
  }
  
  writeValue(value: any): void {
    this.model = value;
  }

  registerOnChange(fn: any): void {
    this.controlChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.controlTouch = fn;
  }


  changeHandle(nextValue:any) {
    this.model = nextValue;
    this.modelChange.emit(nextValue);
    this.controlChange(nextValue);
    this.updateStyles();
  }

  updateStyles() {
    var /** @type {?} */ baseStyle = "width: " + this.realWidth + "px;";
    var /** @type {?} */ translate = this.model ? "translate3d(" + (this.realWidth - 20) + "px, 0, 0)" : '';
    var /** @type {?} */ color = this.model ? this.activeColor : this.inactiveColor;
    var /** @type {?} */ colorStyles = "border-color: " + color + "; background-color: " + color + ";";
    this.iconTransform = this.sanitizer.bypassSecurityTrustStyle("transform: " + translate);
    if (this.activeColor && this.inactiveColor) {
        baseStyle += colorStyles;
    }
    this.coreStyles = this.sanitizer.bypassSecurityTrustStyle(baseStyle);
  }


  ngOnInit(): void {
    this.realWidth = this.width ? this.width : 40;
        this.updateStyles();
  }

}
